package com.steam.job;
import java.io.IOException;
import java.io.InputStream;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import com.google.gson.Gson;
import com.steam.entity.Phone;
import com.steam.entity.临沂送;
import com.steam.entity.临沂送Example;
import com.steam.mapper.ItemMapper;
import com.steam.mapper.临沂送Mapper;
import com.steam.service.JedisClient;
import com.steam.util.GsonBuilderUtil;

//@Component
public class LinyiSpringJob {
	@Autowired
	private RabbitTemplate rabbitTemplate;
	@Autowired
	private JedisClient jedisClient;
	@Autowired
	private ItemMapper itemMapper;

	private static SqlSessionFactory sqlSessionFactory;
	Gson gson = GsonBuilderUtil.create();
	static {
		String resource = "mybatis/LinyiSqlMap.xml";
		InputStream inputStream;
		try {
			inputStream = Resources.getResourceAsStream(resource);
			sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	}
	public boolean isContainChinese(String str) { //判断字符串中是否含有中文
        Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
        Matcher m = p.matcher(str);
        if (m.find()) {
            return true;
        }
        return false;
    }
	public boolean HasDigit(String content) { //判断字符串中是否含有数字
	    boolean flag = false;
	    Pattern p = Pattern.compile(".*\\d+.*");
	    Matcher m = p.matcher(content);
	    if (m.matches()) {
	        flag = true;
	    }
	    return flag;
	}
	/**
	 * 每天的凌晨7点到23点 每隔5秒取出数据
	 */
	@Scheduled(cron = "0/10 * 7-23  * * ? ")
	public void jining() {
		// 数据库会话实例
		SqlSession sqlSession = null;
		临沂送Example example = new 临沂送Example();
		try {
			// 创建数据库会话实例sqlSession
			sqlSession = sqlSessionFactory.openSession();
			Gson gson = GsonBuilderUtil.create();
			//使用mybatis推荐的Mapper接口的方式,而不是使用ibatis的方式
			String jishu = jedisClient.get("linyi");
			if (StringUtils.isNotBlank(jishu)) {
				example.createCriteria().and编号GreaterThan(Integer.parseInt(jishu));
			} else {

			}
			临沂送Mapper mapper = sqlSession.getMapper(临沂送Mapper.class);
			List<临沂送> selectByExamples = mapper.selectByExample(example);
			if(selectByExamples.size()==0){//没有取出数据
				 临沂送 selectByPrimaryKey = mapper.selectByPrimaryKey(Integer.parseInt(jishu));//根据目前的编号来查询
				if(selectByPrimaryKey!=null){
					
				}else{
					临沂送 selectByPrimaryKey2 = mapper.selectByPrimaryKey(Integer.parseInt(jishu));
					if(selectByPrimaryKey2!=null) {
						if(Duration.between(selectByPrimaryKey2.get发送时间1().toInstant(),  Instant.now()).getSeconds()>600){
							
						}else{
							jedisClient.set("linyi","0");
						}
					}
				}
			}else{//如果取出了数据我们遍历数据进行处理
				for (临沂送 tblinfo : selectByExamples) {
					StringBuffer sb = new StringBuffer();
					List<Phone> phone_arr = new ArrayList<>();
					String o_phones = tblinfo.get电话号码();
					String[] phoneList = o_phones.split(" ");
					if(phoneList != null && phoneList.length>0){
	                    for (int i=0;i<phoneList.length;i++){
	                        if(phoneList[i] != " " && !isContainChinese(phoneList[i]) && HasDigit(phoneList[i])){
	                            sb.append(phoneList[i]+" ");
	                            Phone phone = new Phone();
	                            phone.setPhone(phoneList[i]);
	                            phone_arr.add(phone);
	                        }
	                    }
	                }
					com.steam.entity.Item items = new com.steam.entity.Item();
					items.setCreateTime(tblinfo.get发送时间1());// 创建信息的时间
					items.setUserPhones(sb.toString().trim());// 电话信息
					items.setContent(tblinfo.get信息());// 信息的内容
					items.setCity("临沂");//出发地 市
					items.setFormin("临沂");//数据源的来源
					//推送给德州网平台bean
					Item item = new Item();
					item.setContent(tblinfo.get信息());
					item.setPhones(sb.toString().trim());
					item.setTime(tblinfo.get发送时间1());
					User user = new User();
					user.setPhoneList(phone_arr);
					item.setUser(user);
					item.setlTime(tblinfo.get发送时间1().getTime());
					if ("货源".equals(tblinfo.get信息分类())) {// 类型,0是车源,1是货源
						items.setTypeId(1);
						item.setTypeId(1);
					} else {
						items.setTypeId(2);
						item.setTypeId(2);
					}
					try {
						itemMapper.insertSelective(items);
						rabbitTemplate.convertAndSend("*."+items.getFormin(), gson.toJson(item));
					} catch (Exception e) {
						e.printStackTrace();
						jedisClient.set("linyi", tblinfo.get编号().toString());
					}
					jedisClient.set("linyi", tblinfo.get编号().toString());
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			String jishu = jedisClient.get("linyi");
			jedisClient.set("linyi", Integer.parseInt(jishu)+1+"");
		} finally {
			if (sqlSession != null) {
				sqlSession.close();
			}
		}
	}
}